import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:flutter/material.dart";
import "package:flutter_form_builder/flutter_form_builder.dart";

class ClearTextField extends StatefulWidget {
  final String? initialValue;
  final String name;
  final InputDecoration decoration;
  final String? Function(String?)? validator;

  const ClearTextField({
    super.key,
    this.initialValue,
    required this.name,
    this.decoration = const InputDecoration(),
    this.validator,
  });

  @override
  State<ClearTextField> createState() => _ClearTextFieldState();
}

class _ClearTextFieldState extends State<ClearTextField> {
  final GlobalKey<FormBuilderFieldState> textFieldKey =
      GlobalKey<FormBuilderFieldState>();
  final FocusNode focusNode = FocusNode();
  bool _showClear = false;

  @override
  void initState() {
    super.initState();
    focusNode
        .addListener(() => setState(() => _showClear = focusNode.hasFocus));
  }

  @override
  void dispose() {
    super.dispose();
    focusNode.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget? suffixIcon;
    if (_showClear) {
      suffixIcon = GestureDetector(
        onTap: () => textFieldKey.currentState?.didChange(null),
        child: const Padding(
          padding: EdgeInsets.only(right: 10),
          child: Icon(Icons.clear_rounded, color: ThemeVars.colorTextTer),
        ),
      );
    }
    return FormBuilderTextField(
      key: textFieldKey,
      decoration: widget.decoration.copyWith(suffixIcon: suffixIcon),
      focusNode: focusNode,
      initialValue: widget.initialValue,
      name: widget.name,
      validator: widget.validator,
    );
  }
}
